using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Universal.Api.Attributes;
using Universal.Application.Contracts.Dto.Menu;
using Universal.Application.Repositories;
using System.Security.Claims;

namespace Universal.Api.Controllers;

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class MenuController : ControllerBase
{
    private readonly IMenuService _menuService;

    public MenuController(IMenuService menuService)
    {
        _menuService = menuService;
    }

    /// <summary>
    /// 获取当前用户的菜单
    /// </summary>
    [HttpGet("GetCurrentUserMenus")]
    public async Task<IActionResult> GetCurrentUserMenus()
    {
        // 1. 从token中获取用户ID - 尝试多种claim名称
        var userIdClaim = User.FindFirst("sub") ??
                         User.FindFirst(ClaimTypes.NameIdentifier) ??
                         User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");

        if (userIdClaim == null)
        {
            return BadRequest("无效的用户ID: 未找到用户ID claim");
        }

        if (!Guid.TryParse(userIdClaim.Value, out Guid userId))
        {
            return BadRequest($"无效的用户ID: 无法解析 {userIdClaim.Value}");
        }

        // 2. 根据用户ID查找用户角色，然后根据角色查找菜单
        var result = await _menuService.GetUserMenusByUserIdAsync(userId);
        return Ok(result);
    }

    /// <summary>
    /// 获取菜单树
    /// </summary>
    [HttpGet("GetMenuTree")]
    public async Task<IActionResult> GetMenuTree()
    {
        var result = await _menuService.GetMenuTreeAsync();
        return Ok(result);
    }

    /// <summary>
    /// 新增或编辑菜单
    /// </summary>
    [HttpPost("AddOrUpdateMenu")]
    [RequirePermission("menu.Create")]
    public async Task<IActionResult> AddOrUpdateMenu([FromBody] MenuDto dto)
    {
        var result = await _menuService.AddOrUpdateMenuAsync(dto);
        return Ok(result);
    }

    /// <summary>
    /// 删除菜单
    /// </summary>
    [HttpDelete("DeleteMenu/{menuId}")]
    [RequirePermission("menu.Delete")]
    public async Task<IActionResult> DeleteMenu(Guid menuId)
    {
        var result = await _menuService.DeleteMenuAsync(menuId);
        return Ok(result);
    }

    /// <summary>
    /// 恢复默认菜单
    /// </summary>
    [HttpPost("RestoreDefaultMenus")]
    public async Task<IActionResult> RestoreDefaultMenus()
    {
        var result = await _menuService.RestoreDefaultMenusAsync();
        return Ok(result);
    }

    [HttpPut("EnableMenu/{menuId}")]
    [RequirePermission("menu.Edit")]
    public async Task<IActionResult> EnableMenu(Guid menuId)
    {
        var result = await _menuService.EnableMenuAsync(menuId);
        return Ok(result);
    }

    [HttpPut("DisableMenu/{menuId}")]
    [RequirePermission("menu.Edit")]
    public async Task<IActionResult> DisableMenu(Guid menuId)
    {
        var result = await _menuService.DisableMenuAsync(menuId);
        return Ok(result);
    }

}